<template>
  <a-modal
    title="新增兑换码"
    :width="560"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :destroyOnClose="true"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item label="兑换码库" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select v-decorator="['exchange_id', { rules: [{ required: true, message: '请选择兑换码库' }] }]">
            <a-select-option v-for="(item, index) in resourceArray" :key="index" :value="item.id">{{
              item.name
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="生成兑换码数量" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-number
            v-decorator="['num', { rules: [{ required: true, message: '请输入生成兑换码数量' }] }]"
            :style="{ width: '100%' }"
          />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import * as Api from '@/api/gift'
export default {
  props: {},
  data() {
    return {
      // 对话框标题
      title: '',
      // 标签布局属性
      labelCol: {
        span: 6,
      },
      // 输入框布局属性
      wrapperCol: {
        span: 18,
      },
      // modal(对话框)是否可见
      visible: false,
      // modal(对话框)确定按钮 loading
      confirmLoading: false,
      // 当前表单元素
      form: this.$form.createForm(this),

      resourceArray: [],
    }
  },

  mounted() {
    this.getResource()
  },

  methods: {
    // 显示对话框
    add() {
      // 显示窗口
      this.visible = true
    },

    getResource() {
      Api.exchange().then((result) => {
        this.resourceArray = result.data.list.data
      })
    },

    // 确认按钮
    handleSubmit(e) {
      e.preventDefault()
      // 表单验证
      const {
        form: { validateFields },
      } = this
      validateFields((errors, values) => {
        // 提交到后端api
        if (!errors) {
          this.onFormSubmit(values)
        }
      })
    },

    // 关闭对话框事件
    handleCancel() {
      this.visible = false
      this.form.resetFields()
    },

    // 提交到后端api
    onFormSubmit(values) {
      this.confirmLoading = true
      Api.add({ form: values })
        .then((result) => {
          // 显示成功
          this.$message.success(result.message, 1.5)
          // 关闭对话框事件
          this.handleCancel()
          // 通知父端组件提交完成了
          this.$emit('handleSubmit', values)
        })
        .finally((result) => {
          this.confirmLoading = false
        })
    },
  },
}
</script>
